package marchenko.lab1.main;


import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;

public class TestModuleFactory {
	
	public static final String className = "marchenko.lab1.main.TestModule";
	
	private static void compile() {
        List<String> files1 = new ArrayList<String>();
        String path = ("src/"+className).replace('.', '/')+".java";
        files1.add(path);
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
        Iterable<? extends JavaFileObject> compilationUnits1 = fileManager.getJavaFileObjectsFromStrings(files1);
        List<String> lstout = new ArrayList<String>(Arrays.asList("-d","bin"));
        compiler.getTask(null, fileManager, null, lstout, null, compilationUnits1).call();
	}
	
	public static Object newInstance() {
		compile();
	    URLClassLoader tmp = new URLClassLoader(new URL[] {getClassPath()}) {
	      @Override
	      public
	      synchronized Class<?> loadClass(String name)
	      throws ClassNotFoundException {
	        if (className.equals(name))
	          return findClass(name);
	        return super.loadClass(name);
	      }
	    };

	    try {
	      return tmp.loadClass(className).newInstance();
	    } catch (InstantiationException e) {
	      throw new RuntimeException(e.getCause());
	    } catch (IllegalAccessException e) {
	      throw new RuntimeException(e);
	    } catch (ClassNotFoundException e) {
	      throw new RuntimeException(e);
	    }
	  }

	  private static URL getClassPath() {
	    String resName = 
	      TestModuleFactory.class.getName().replace('.', '/') + ".class";
	    String loc = 
	    	TestModuleFactory.class.getClassLoader().getResource(resName)
	      .toExternalForm();    
	    URL cp;
	    try {
	      cp = new URL(loc.substring(0, loc.length() - resName.length()));
	    } catch (MalformedURLException e) {
	      throw new RuntimeException(e);
	    }
	    return cp;
	  }
}
